package com.njdj.gps.web.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.njdj.gps.kernel.entity.SeUser;
import com.njdj.gps.kernel.service.ICreateIdService;
import com.njdj.gps.kernel.service.ISeUserService;
import com.njdj.gps.record.QueryCarHistory;
import com.njdj.gps.record.task.SaveCarHistory;
import com.njdj.gps.web.resource.AdminResource;


@Controller
public class UserController extends BaseController {
	
	@Autowired
	ICreateIdService createIdService;
	@Autowired
	AdminResource adminResource;
	@Autowired
	ISeUserService seUserService;
	
	@RequestMapping("/login.do")
	public ModelAndView loginHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws ServletException, DocumentException {
		String action = this.getParameter(request, "action");
		if(null != action && "do".equals(action)){
			String username = this.getParameter(request, "username");
			String password = this.getParameter(request, "password");
			if(null != username && !"".equals(username) && null != password && !"".equals(password)){
				Map<String, Object> param = new HashMap<String,Object>();
				param.put("username", username);
				param.put("password", password);
				param.put("status", 0);
				SeUser seUser = seUserService.getModel(param);  //进行验证
				if(null != seUser && null != seUser.getUsername() && !"".equals(seUser.getUsername())){
					this.setSessionObject(request, "userName", seUser.getUsername());  //设置用户名
					if(null != seUser.getFullname() && !"".equals(seUser.getFullname()))
					this.setSessionObject(request, "fullName", seUser.getFullname());  //设置全名
					Map<String,String> adminMap = adminResource.getAdminMap();
					if(null != adminMap && null != adminMap.get("administrator") && adminMap.get("administrator").equals(seUser.getUsername())){
						this.setSessionObject(request, "role", "administrator");
					} else
						this.setSessionObject(request, "role", "user");
					return new ModelAndView("redirect:home.do");
				} else
					return new ModelAndView("redirect:login.do");
			} else
				return new ModelAndView("redirect:login.do");
		}
		return new ModelAndView("login");
	}

}
